import {
  _decorator,
  Component,
  EventKeyboard,
  EventTouch,
  Input,
  input,
  KeyCode,
  log,
  Node,
  UITransform,
  v3,
} from 'cc'
const { ccclass, property } = _decorator

@ccclass('NodeEvent')
export class NodeEvent extends Component {
  start() {
    // 触摸事件
    this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this)
    this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
    this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
    this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this)

    // 输入事件
    input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this)
  }

  onKeyDown(event: EventKeyboard) {
    log(event.keyCode === KeyCode.KEY_W)
  }

  onTouchStart(event: EventTouch) {
    const uiPos = event.getUILocation()
    log('onTouchStart')
    // 点击图片偏左右，图片跟随移动效果
    const transform = this.node.getComponent(UITransform)
    // 将屏幕坐标转换为节点坐标
    const nodePos = transform.convertToNodeSpaceAR(v3(uiPos.x, uiPos.y, 0))
    log(nodePos, 20)
    // 判断点击位置在节点的左边还是右边
    if (nodePos.x > 0) {
      this.node.setPosition(this.node.position.x + 50, this.node.position.y)
    } else {
      this.node.setPosition(this.node.position.x - 50, this.node.position.y)
    }
  }

  onTouchMove(event: EventTouch) {
    log('onTouchMove')

    // 按住拖拽效果
    // const delta = event.getUIDelta()
    // const dx = delta.x
    // const dy = delta.y
    // const x = this.node.position.x
    // const y = this.node.position.y
    // this.node.setPosition(x + dx, y + dy)
  }

  onTouchEnd(event: EventTouch) {
    log('onTouchEnd')
    // this.node.setScale(1, 1)
  }

  onTouchCancel(event: EventTouch) {
    log('onTouchCancel')
    // this.node.setScale(1, 1)
  }

  update(deltaTime: number) {}
}
